<template>
  <el-tabs v-model="activeTab" class="configtab">
    <el-tab-pane label="基础" name="base">
      <el-form size="small" label-position="top" ref="baseform" :model="component.bsChartInfo">
        <el-form-item label="组件标题">
          <el-input v-model="component.bsChartInfo.name"></el-input>
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="宽度">
              <el-input v-model="component.bsChartInfo.width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="高度">
              <el-input v-model="component.bsChartInfo.height"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="X轴坐标">
              <el-input v-model="component.bsChartInfo.x"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Y轴坐标">
              <el-input v-model="component.bsChartInfo.y"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="刷新频率">
              <el-input v-model="component.bsChartInfo.refreshTime"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否加边框">
              <el-color-picker v-model="chartConfig.style.border"></el-color-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="柱条宽度">
              <el-input v-model="chartConfig.barWidth"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="颜色">
              <el-color-picker v-model="chartConfig.style.color"></el-color-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="text-align:center">
          <el-button type="danger" @click="remove">删除组件</el-button>
          <el-button type="primary" @click="submit">保存更改</el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>
    <el-tab-pane label="数据" name="config">
      <el-form size="small" label-position="top" ref="dataform" :model="component.bsChartComponent">
        <el-form-item label="数据源">
          <el-radio-group
            v-model="component.bsChartComponent.bindDataType"
            @change="resetDatabases"
          >
            <el-radio-button :label="1">SQL建模</el-radio-button>
            <el-radio-button :label="2">API拉取</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="根据名称选择数据">
          <el-select
            v-model="component.bsChartComponent.bindDataId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            @change="setSource"
            :remote-method="remoteMethod"
          >
            <el-option
              v-for="item in pickdatasource"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Y轴" v-if="fieldMapping.length > 0" class="sys-zhou">
          <el-select v-model="chartConfig.x" placeholder="请选择">
            <el-option
              v-for="item in fieldMapping"
              :key="item.field_name"
              :label="item.show_name"
              :value="item.field_name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="当前值 / 最大值"
          class="sys-zhou"
        >
          <el-select v-model="chartConfig.data.value1" placeholder="请选择">
            <el-option
              v-for="item in fieldMapping"
              :key="item.field_name"
              :label="item.show_name"
              :value="item.field_name"
            ></el-option>
          </el-select>
          <el-select v-model="chartConfig.data.value2" placeholder="请选择">
            <el-option
              v-for="item in fieldMapping"
              :key="item.field_name"
              :label="item.show_name"
              :value="item.field_name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="text-align:center">
          <el-button type="success" @click="handleTest">调试</el-button>
          <el-button type="primary" @click="submitConfig">保存更改</el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>
  </el-tabs>
</template>
<script>
import { mapMutations } from "vuex";
import Services from "@/services";
export default {
  name: "CbarConfig",
  props: {
    component: Object,
    datasource: Array,
    drillsource: Array
  },
  data() {
    return {
      activeTab: "base",
      fieldMappingRS: [],
      dataMappingRS: [],
      drillSourceDefault: [],
      chartConfig: {
        style: {
          border: null
        },
        barWidth: "auto",
        x: "",
        y: []
      },
      drillParams: {
        key: "",
        value: ""
      }
    };
  },
  computed: {
    pickdatasource: {
      get() {
        if (this.datasource.length > 0) {
          return this.datasource;
        } else {
          if (this.component.bsChartComponent.bindDataType == 1) {
            if (this.component.bsChartComponent.dsSqlDO) {
              return [
                {
                  id: this.component.bsChartComponent.dsSqlDO.id,
                  name: this.component.bsChartComponent.dsSqlDO.name
                }
              ];
            } else {
              return [];
            }
          }
          if (this.component.bsChartComponent.bindDataType == 2) {
            if (this.component.bsChartComponent.bsApiInfoDO) {
              return [
                {
                  id: this.component.bsChartComponent.bsApiInfoDO.id,
                  name: this.component.bsChartComponent.bsApiInfoDO.name
                }
              ];
            } else {
              return [];
            }
          }
        }
      }
    },
    pickdrillsource: {
      get() {
        if (this.drillsource.length > 0) {
          // console.log(this.drillsource)
          return this.drillsource;
        } else {
          if (this.drillSourceDefault.length > 0) {
            let dataMappingStr = this.drillSourceDefault[0].dataMapping.replace(
              /'/g,
              '"'
            );
            this.dataMappingRS = JSON.parse(dataMappingStr);
          }
          return this.drillSourceDefault;
        }
      }
    },

    fieldMapping: {
      get() {
        if (this.fieldMappingRS.length > 0) {
          return this.fieldMappingRS;
        } else if (
          this.component.bsChartComponent.bindDataType == 1 &&
          this.component.bsChartComponent.dsSqlDO
        ) {
          return JSON.parse(
            this.component.bsChartComponent.dsSqlDO.fieldMapping
          );
        } else if (
          this.component.bsChartComponent.bindDataType == 2 &&
          this.component.bsChartComponent.bsApiInfoDO
        ) {
          console.log(this.component.bsChartComponent.bsApiInfoDO.fieldMapping);
          return JSON.parse(
            this.component.bsChartComponent.bsApiInfoDO.fieldMapping
          );
        } else {
          return [];
        }
      }
    },
    drillMapping: {
      get() {
        if (this.dataMappingRS.length > 0) {
          return this.dataMappingRS;
        } else {
          return [];
        }
      }
    }
  },
  methods: {
    ...mapMutations({
      CHARTS_UPDATE: "charts/UPDATE"
    }),
    remove() {
      this.$emit("remove", this.component.bsChartInfo.id);
    },
    // 调用数据源
    remoteMethod(e) {
      if (e.length > 1) {
        this.$emit("remote", e, this.component);
      }
    },
    // 调用下钻
    remoteDrill(e) {
      if (e.length > 1) {
        this.$emit("drill", e, this.component);
      }
    },
    // 测试
    handleTest() {
      if (this.component.bsChartComponent.bindDataType == 1) {
        Services.SQL_TEST(this.component.bsChartComponent.dsSqlDO).then(res => {
          if (res.code === 0) {
            this.$message.success(res.msg);
          } else {
            this.$message.error(res.msg);
          }
        });
      } else {
        Services.API_TEST({
          id: this.component.bsChartComponent.bindDataId
        }).then(res => {
          this.$message.success(res.msg);
        });
      }
    },
    // 保存数据
    submitConfig(e) {
      let chartConfig = this.formateChartConfig();
      this.submit(e, { type: "chart", config: chartConfig });
    },

    // 保存高级
    submitDrill(e) {
      let drillConfig = this.formateDrill();
      this.submit(e, { type: "drill", config: drillConfig });
    },
    // 保存基础
    submit(e, update) {
      if (update && update.type === "drill") {
        this.$emit("saveDrill", this.component.bsChartInfo.id, update.config);
      } else {
        this.$emit(
          "saveConfig",
          this.component.bsChartInfo.id,
          update ? update.config : null
        );
      }
    },
    //  格式化图表数据
    formateChartConfig() {
      let chartConfig = JSON.stringify(this.chartConfig);
      return chartConfig;
    },

    // 切换数据源后重置
    resetDatabases(e) {
      this.databases = [];
      if (e != this.component.bsChartComponent.bindDataType) {
        this.fieldMappingRS = [];
      } else {
        this.fieldMappingRS = [];
      }
    },
    //  设置数据源
    setSource(e) {
      this.datasource.forEach(database => {
        if (database.id == e) {
          let fieldMappingStr = database.fieldMapping.replace(/'/g, '"');
          this.fieldMappingRS = JSON.parse(fieldMappingStr);
          this.chartConfig = {
            ...this.chartConfig,
            x: "",
            y: []
          };
        }
      });
    },
    // 设置下钻
    setDrill(e) {
      this.drillsource.forEach(drill => {
        if (drill.id == e) {
          let dataMappingStr = drill.dataMapping.replace(/'/g, '"');
          this.dataMappingRS = JSON.parse(dataMappingStr);
        }
      });
    },
    // 格式化下钻数据参数
    formateDrill() {
      return (
        '{"' + this.drillParams.key + '":"' + this.drillParams.value + '"}'
      );
    },
    // 新增值
    addY() {
      // console.log(this.chartConfig)
      this.chartConfig.y.push({
        name: "",
        color: "auto"
      });
    },
    //  删除值
    removeY(index) {
      this.chartConfig.y.splice(index, 1);
    }
  },
  watch: {
    // 监听组件变化
    component: {
      handler(n, o) {
        const ncomponent = this.component;
        // 设置默认选中的 数据 配置
        let defaultChartConfig = JSON.parse(
          ncomponent.bsChartComponent.chartConfig
        );
        this.chartConfig = {
          ...this.chartConfig,
          ...defaultChartConfig
        };
        // 设置默认选中的 下钻 配置
        if (ncomponent.bsChartComponent.isDrill === 1) {
          if (ncomponent.bsChartComponent.drillParams) {
            let defaultDrillParams = JSON.parse(
              ncomponent.bsChartComponent.drillParams
            );
            this.drillParams.key = Object.keys(defaultDrillParams)[0];
            this.drillParams.value = Object.values(defaultDrillParams)[0];
          }
          Services.DRILL_GET({
            id: ncomponent.bsChartComponent.drillChartId
          }).then(res => {
            this.drillSourceDefault = [res];
          });
        }

        this.CHARTS_UPDATE(ncomponent);
      },
      immediate: true,
      deep: true
    },
    // 监听图表配置变化
    chartConfig: {
      handler(n, o) {
        let newconfig = this.formateChartConfig();
        let componentClone = Object.assign({}, this.component);
        if (newconfig) {
          componentClone.bsChartComponent.chartConfig = newconfig;
          this.CHARTS_UPDATE(componentClone);
        }
      },
      deep: true
    },
    // 监听下钻变化
    drillParams: {
      handler(n, o) {
        let newdirllparams = this.formateDrill();
        let componentClone = Object.assign({}, this.component);
        if (newdirllparams) {
          componentClone.bsChartComponent.drillParams = newdirllparams;
          this.CHARTS_UPDATE(componentClone);
        }
      },
      deep: true
    }
  }
};
</script>
<style lang="less">
.sys-zhou {
  .el-form-item__content {
    display: flex;
    .el-color-picker {
      margin-left: 10px;
    }
  }
}
</style>

